home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 3 / BBS in a box - Trilogy III.iso / Files / Prog / B-C / C++ FAQ Reference 1.0 / C++ FAQ Reference 1.0.rsrc / TEXT_1234.txt < prev    next >
Encoding:
Text File  |  1993-06-30  |  1.8 KB  |  25 lines

  1. Yes, there are some practices which are generally considered dangerous. However none of these are universally 'bad', since situations arise when even the worst of these is needed:
  2.  * a class 'X's assignment operator should return '*this' as an 'X&'    (allows chaining of assignments)
  3.  * a class with any virtual fns ought to have a virtual destructor
  4.  * a class with any of {dtor, assignment-op, copy-ctor} generally needs all 3
  5.  * a class 'X's copy-ctor and assignment-op should have 'const' in the param:
  6.    'X::X(const X&)'  and  'X& X::operator=(const X&)'  respectively
  7.  * always use initialization lists for class sub-objects rather than assignment    the performance difference for user-defined classes can be substantial (3x!)
  8.  * many assignment operators should start by testing if 'we' are 'them'; ex:
  9.     X& X::operator=(const X& x)
  10.     {
  11.       if (this == &x) return *this;
  12.       //...normal assignment duties...
  13.       return *this;
  14.     }
  15.    sometimes there is no need to check, but these situations generally    correspond to when there's no need for an explicit user-specified assignment    op (as opposed to a compiler-synthesized assignment-op).
  16.  * in classes that define both '+=', '+' and '=', 'a+=b' and 'a=a+b' should    generally do the same thing; ditto for the other identities of builtin types    (ex: a+=1 and ++a; p[i] and *(p+i); etc).  This can be enforced by writing    the binary ops using the 'op=' forms; ex:
  17.     X operator+(const X& a, const X& b)
  18.     {
  19.       X ans = a;
  20.       ans += b;
  21.       return ans;
  22.     }
  23.    This way the 'constructive' binary ops don't even need to be friends.  But    it is sometimes possible to more efficiently implement common ops (ex: if    'X' a 'String' and '+=' has to reallocate/copy string memory, it's better to    know the eventual length from the beginning).
  24.  
  25. See Stroustrup/C++ Programming Language/Second Edition/'Rules of Thumb'/p.10